import { Component, Emit, Prop, Ref, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'

import toNative from '@/utils/toNative'

import Dialog from '@/components/dialog/Index'

import type { ComponentPublicInstance } from 'vue'
import { getNeedSyncInvoiceList, getNeedUploadList, syncInvoice } from '@/api/invoice'
import {
    getModelValue,
    initModelValue,
    renderForm,
    type FormModalDto
} from '@/components/modal/Modal'
import type { BatchInvoiceDto, InvoiceDto, SyncInvoiceReqDto } from '@/api/invoice/types'
import PreviewImageOrPdf, { type BtnType } from '@/components/preview-media/PreviewImageOrPdf'
import { InvoiceTypeCnEnum } from '@/const/enum'
import { Button, Checkbox, Col, Empty, message, Row } from 'ant-design-vue'
import { VxeColumn, VxeGrid, VxeTable, type VxeGridMethods } from 'vxe-table'
import { wait } from '@/utils/util'
import { CloseOutlined } from '@ant-design/icons-vue'

interface InvoiceExtendDto extends InvoiceDto {
    isChecked: boolean
    disabled: boolean
    disableId: number
}

interface SelectedType extends InvoiceExtendDto {
    batchInvoice: BatchInvoiceDto
}

@Component
export class DialogHandleConflictInvoice extends Render {
    @Prop({ default: false }) show!: boolean
    @Prop() invoicelist!: BatchInvoiceDto[]
    @Prop() showDate!: boolean
    @Ref() ref!: VxeGridMethods

    showDialog = false

    active = 0

    batchInvoiceList: BatchInvoiceDto[] = []
    needUploadList: InvoiceExtendDto[] = []
    selectedList: SelectedType[] = []

    checkboxConfig = {
        labelField: 'invoiceName',
        checkMethod: (params: any) => {
            return !params.row.disabled
        }
    }

    @Emit('update:show')
    emitShow(val: boolean) {
        return val
    }

    @Emit('refresh')
    handleRefresh() {}

    @Watch('invoicelist')
    async handleWatchBatchInvoicelist(val: BatchInvoiceDto[]) {
        if (!this.invoicelist.length) {
            this.clear()
        } else {
            this.batchInvoiceList = this.invoicelist
            this.needUploadList = await this.getUploadList(this.batchInvoiceList[0])
        }
    }

    @Watch('show', { immediate: true })
    async handleWatchShow() {
        this.showDialog = this.show
        if (this.show) {
            this.basicForm = renderForm(this.basicFormConfig)
        } else {
            this.clear()
        }
    }

    @Watch('showDialog', { immediate: true })
    handleWatchDialogShow() {
        this.emitShow(this.showDialog)
    }

    basicFormConfig = this.initBasicFormConfig() as FormModalDto
    initBasicFormConfig() {
        return {
            title: '',
            width: '400px',
            theme: 'light',
            show: false,
            noPadding: true,
            items: {
                month: {
                    name: '',
                    element: 'datetime',
                    type: 'month',
                    span: 6,
                    callback: {
                        change: async () => {
                            this.batchInvoiceList = await this.getInvoiceList()
                            this.needUploadList = this.batchInvoiceList?.length
                                ? await this.getUploadList(this.batchInvoiceList[0])
                                : []
                        }
                    }
                }
            },
            complete: async () => {},
            cancel: () => {
                this.basicFormConfig.show = false
            },
            init: () => {
                initModelValue(this.basicFormConfig)
            }
        } as FormModalDto
    }

    basicForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    get totalMoney() {
        const curList = this.selectedList.filter((i) => {
            return i.batchInvoice.id === this.batchInvoiceList[this.active].id
        })
        console.log(1234, curList)
        return curList.reduce((a, b) => a + b.amount, 0) || 0
    }

    clear() {
        this.needUploadList = []
        this.selectedList = []
        this.active = 0
    }

    async getInvoiceList() {
        const params = getModelValue(this.basicFormConfig)
        const res = await getNeedSyncInvoiceList({
            isSync: 0,
            month: params.month
        })
        return res
    }

    async getUploadList(params: BatchInvoiceDto | InvoiceExtendDto) {
        const res = (await getNeedUploadList({
            companyName: params.companyName,
            voiceType: params.type
        })) as InvoiceExtendDto[]
        res.forEach((i) => {
            i.isChecked = false
            i.disabled = false
            i.disableId = params.id
        })
        this.selectedList.forEach((i) => {
            const index = res.findIndex((j) => j.id === i.id)
            if (index !== -1) {
                const curSelect = res[index]
                if (
                    i.companyName === curSelect.companyName &&
                    i.type === curSelect.type &&
                    i.disableId !== curSelect.disableId
                ) {
                    curSelect.disabled = true
                } else {
                    curSelect.isChecked = true
                }
            }
        })
        return res
    }

    async onChange(item: BatchInvoiceDto, index: number) {
        this.active = index
        this.needUploadList = await this.getUploadList(item)
        await wait(100)
        if (this.needUploadList.length) {
            const index = this.needUploadList.findIndex((item) =>
                this.selectedList.find((i) => i.id === item.id)
            )
            if (index !== -1) {
                this.ref.setCheckboxRow(this.needUploadList[index], true)
            }
        }
    }

    onCheckboxChange() {
        this.selectedList = this.ref.getCheckboxRecords() as SelectedType[]
        this.selectedList.forEach((item) => {
            item.batchInvoice = this.batchInvoiceList[this.active]
        })
    }

    onCheckboxAll() {
        this.selectedList = this.ref.getCheckboxRecords() as SelectedType[]
        this.selectedList.forEach((item) => {
            item.batchInvoice = this.batchInvoiceList[this.active]
        })
    }

    onCancel() {
        this.showDialog = false
    }

    async onConfirm() {
        if (!this.selectedList?.length) {
            message.warning('请先选择发票')
            return
        }

        const params = [] as SyncInvoiceReqDto[]
        this.selectedList.forEach((i) => {
            const index = params.findIndex((k) => k.uploadId === i.batchInvoice.id)
            if (index !== -1) {
                params[index].invoiceList.push({
                    id: i.id,
                    month: i.month,
                    status: i.status
                })
            } else {
                const data = {
                    uploadId: i.batchInvoice.id,
                    invoiceUrl: i.batchInvoice.invoiceUrl,
                    invoiceList: [
                        {
                            id: i.id,
                            month: i.month,
                            status: i.status
                        }
                    ]
                }
                params.push(data)
            }
        })

        await syncInvoice(params)
        this.showDialog = false
        this.handleRefresh()
    }

    onClear() {
        this.selectedList = []
        this.ref.clearCheckboxRow()
    }

    onRemove(row: InvoiceDto, index: number) {
        this.selectedList.splice(index, 1)
        this.ref.setCheckboxRow(row, false)
    }

    render(data: ComponentPublicInstance) {
        return (
            <Dialog
                v-model:show={this.showDialog}
                title="冲突发票处理"
                width={1100}
                v-slots={{
                    default: () => {
                        return (
                            <>
                                <div>{this.showDate && this.basicForm.element()}</div>
                                <Row class="text-base" gutter={20}>
                                    <Col md={14} sm={24}>
                                        <div class="p-10px border-1 rounded-lg">
                                            <Row>
                                                <Col
                                                    md={14}
                                                    sm={24}
                                                    class="max-h-500px overflow-auto"
                                                >
                                                    {this.batchInvoiceList?.length ? (
                                                        this.batchInvoiceList.map((i, index) => {
                                                            return (
                                                                <div
                                                                    class={`px-16px py-10px mb-12px cursor-pointer ${this.active === index ? 'bg-blue-100 text-blue-default !bg-opacity-20 rounded-sm' : ''}`}
                                                                    onClick={() =>
                                                                        this.onChange(i, index)
                                                                    }
                                                                >
                                                                    <Row>
                                                                        <Col lg={18} md={24}>
                                                                            <div
                                                                                class="truncate font-bold"
                                                                                title={
                                                                                    i.companyName
                                                                                }
                                                                            >
                                                                                {i.companyName}
                                                                            </div>
                                                                        </Col>
                                                                        <Col lg={6} md={24}>
                                                                            <PreviewImageOrPdf
                                                                                src={i.invoiceUrl}
                                                                                text="预览"
                                                                                type="primary"
                                                                            />
                                                                        </Col>
                                                                        <Col lg={12} md={24}>
                                                                            产品类型：
                                                                            {
                                                                                InvoiceTypeCnEnum[
                                                                                    i.type
                                                                                ]
                                                                            }
                                                                        </Col>
                                                                        <Col lg={12} md={24}>
                                                                            发票月份：{i.month}
                                                                        </Col>
                                                                    </Row>
                                                                </div>
                                                            )
                                                        })
                                                    ) : (
                                                        <div class="text-center">
                                                            <Empty />
                                                        </div>
                                                    )}
                                                </Col>
                                                <Col
                                                    md={10}
                                                    sm={24}
                                                    class="max-h-500px overflow-auto"
                                                >
                                                    <VxeTable
                                                        ref="ref"
                                                        data={this.needUploadList}
                                                        border="none"
                                                        onCheckboxChange={this.onCheckboxChange}
                                                        onCheckboxAll={this.onCheckboxAll}
                                                        checkboxConfig={this.checkboxConfig}
                                                    >
                                                        <VxeColumn
                                                            type="checkbox"
                                                            width="150"
                                                            title="发票月份"
                                                        ></VxeColumn>
                                                        {/* <VxeColumn
                                                            field="invoiceName"
                                                            width="120"
                                                            title="发票月份"
                                                        ></VxeColumn> */}
                                                        <VxeColumn
                                                            field="amount"
                                                            title="发票金额"
                                                            formatter={({ row }) =>
                                                                row.amount || row.amount === 0
                                                                    ? '¥' + row.amount
                                                                    : ''
                                                            }
                                                        ></VxeColumn>
                                                    </VxeTable>
                                                    {this.totalMoney ? (
                                                        <div class="text-right mr-20px text-black-200 pt-12px border-t-1 border-t-solid border-t-border-color-100">
                                                            合计：
                                                            <span class="">
                                                                ¥{this.totalMoney ?? 0}
                                                            </span>
                                                        </div>
                                                    ) : (
                                                        <></>
                                                    )}
                                                </Col>
                                            </Row>
                                        </div>
                                    </Col>
                                    <Col md={10} sm={24} class="h-500px overflow-auto">
                                        <div class="p-10px border-1 rounded-lg">
                                            <div class="flex justify-between">
                                                <div class="flex-1">共选择：{this.selectedList.length}个</div>
                                                {this.selectedList.length ? (
                                                    <Button type="link" onClick={this.onClear}>全部清除</Button>
                                                ) : (
                                                    <></>
                                                )}
                                                <div></div>
                                            </div>
                                            {this.selectedList.length ? (
                                                this.selectedList.map((i, index) => {
                                                    return (
                                                        <div class="flex items-center">
                                                            <div class="py-10px flex-1">
                                                                <div class="flex justify-between">
                                                                    <div
                                                                        class="truncate font-bold"
                                                                        title={i.companyName}
                                                                    >
                                                                        {i.companyName}
                                                                    </div>
                                                                    <PreviewImageOrPdf
                                                                        src={i.batchInvoice?.invoiceUrl}
                                                                        text="预览"
                                                                        type="primary"
                                                                    />
                                                                </div>
                                                                <div class="flex">
                                                                    <div>
                                                                    产品类型：
                                                                        {InvoiceTypeCnEnum[i.type]}
                                                                    </div>
                                                                    <div class="ml-20px">
                                                                    发票月份：{i.month}
                                                                    </div>
                                                                </div>
                                                                <div class="flex">
                                                                    <div>
                                                                    应用月份：{i.batchInvoice.month}
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div class="px-10px cursor-pointer" onClick={() => this.onRemove(i, index)}>
                                                                <CloseOutlined />
                                                            </div>
                                                        </div>
                                                    )
                                                })
                                            ) : (
                                                <Empty />
                                            )}
                                        </div>
                                    </Col>
                                </Row>
                            </>
                        )
                    },
                    footer: () => {
                        return (
                            <div class="flex justify-center">
                                <Button type="primary" onClick={this.onConfirm}>
                                    确定
                                </Button>
                            </div>
                        )
                    }
                }}
            ></Dialog>
        )
    }
}

export default toNative<
    { invoicelist: (InvoiceDto | BatchInvoiceDto)[]; showDate: boolean },
    { confirm: () => void }
        >(DialogHandleConflictInvoice)
